const path = require('path');
const express = require('express');
const bodyParser = require('body-parser');
const chokidar = require('chokidar');
const chalk = require('chalk');


require('./models');
const initRoutes = require('./routes');
const { clearRequireCache, logger } = require('./utils');
require('express-async-errors');

process.logger = logger;

module.exports = (app) => {
  // respond with "hello world" when a GET request is made to the homepage
  // app.get(process.env.VUE_APP_BASE_API, function(req, res) {
  //   res.status(200).json({
  //     success: true
  //   })
  // })
  require('./models');
  if (!app) {
    app = express();
  }
  app.use(
    '/logs',
    express.static(path.join(__dirname, './logs')),
  );
  app.use(bodyParser.json({ limit: '100mb' }));
  app.use(bodyParser.urlencoded({
    extended: true,
  }));


  // 拦截接口请求，修改请求类型
  app.use(`${process.env.VUE_APP_BASE_API}/*`, (req, res, next) => {
    req.headers.accept = 'application/json, text/plain, */*';
    next();
  });

  let uninstallRoutes = initRoutes(app);

  if (process.env.NODE_ENV === 'development') {
    const routesDir = path.resolve(__dirname, 'routes');
    const serviceDir = path.resolve(__dirname, 'service');
    chokidar.watch([routesDir, serviceDir], {
      ignoreInitial: true,
    }).on('all', (event, path) => {
      if (event === 'change' || event === 'add') {
        try {
          // remove mock routes stack
          uninstallRoutes();
          // clear routes cache
          clearRequireCache([routesDir, serviceDir]);

          uninstallRoutes = initRoutes(app);


          console.log(chalk.greenBright(`\n > 服务热更新成功！ 文件： ” ${path} “ 已更新`));
        } catch (error) {
          console.log(chalk.redBright(error));
        }
      }
    });
  }
  return app;
};
